package a_doubleWrite;

import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;

/**
 * 丑数2
 *
 * @author luolidong
 * @version 1.0
 * @create 2021-08-02 19:17
 */
public class L264 {
//    time: nlogn
    public int nthUglyNumber(int n) {
        //虽然返回值不会越界，但是要*2,3,5入堆可能越界
        Queue<Long> queue = new PriorityQueue<>();
        Set<Long> set = new HashSet<>();
        queue.offer(1L);
        set.add(1L);
        int[] nums = new int[]{2, 3, 5};
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            //每次弹出最小值
            long poll = queue.poll();
            //第n次弹出即为第i小
            if (i == n) {
                ans = (int)poll;
            }
            for (int num : nums) {
                long i1 = num * poll;
                if (!set.contains(i1)) {
                    set.add(i1);
                    queue.offer(i1);
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        L264 l264 = new L264();
        int i = l264.nthUglyNumber(20);

    }
}
